<?php
/*
 * 角色管理
 */
namespace Admin\Controller;

use Common\Controller\AdminBaseController;
use Common\Lib\Util\File;

class SettingController extends AdminBaseController
{
    const SITE_KEY    = 'site_settings';
    const MAIL_KEY    = 'mail_settings';
    const UPLOAD_KEY  = 'upload_settings';
    const STORAGE_KEY = 'storage_settings';

    protected $setting_model;

    public function _initialize() {
        parent::_initialize();
        $this->setting_model = D("Common/Setting");
    }

    /*
     * 站点基本设置
     * */
    public function site() {

        if (IS_POST) {
            $post = I('post.', array(), 'trim');
            if (empty($post)) {
                $this->error('请填写设置的值');
            }
            $data = array(
                'key'   => self::SITE_KEY,
                'value' => json_encode($post)
            );
            if ($this->setting_model->save($data) !== false) {
                $this->success('设置成功', U('site'));
            } else {
                $this->error('设置失败');
            }
        } else {
            //读取前台模板
            $dirinfo   = File::get_dirs(C('X_TMPL_PATH'));
            $templates = $dirinfo['dir'];
            $noneed = array(".","..",".svn");
            $templates = array_diff($templates, $noneed);
            $this->assign("templates",$templates);

            $setting = $this->setting_model->getSettingByKey(self::SITE_KEY);
            $this->assign($setting);
            $this->display();
        }
    }

    /*
     * 邮箱SMTP配置设置
     * */
    public function mail() {
        if (IS_POST) {
            $post = I('post.', array(), 'trim');
            if (empty($post)) {
                $this->error('请填写设置的值');
            }
            $data = array(
                'key'   => self::MAIL_KEY,
                'value' => json_encode($post)
            );
            if ($this->setting_model->save($data) !== false) {
                $this->success('设置成功', U('mail'));
            } else {
                $this->error('设置失败');
            }
        } else {
            $setting = $this->setting_model->getSettingByKey(self::MAIL_KEY);
            $this->assign('detail', $setting);
            $this->display();
        }
    }

    /*
     * 测试发送邮件
     * */
    public function mailTest() {
        if (IS_POST) {
            $rules = array(
                array('send_to', 'require', '收件箱不能为空', 1, 'regex', 3),
                array('send_to', 'email', '收件箱格式不正确', 1, 'regex', 3),
                array('subject', 'require', '邮件标题不能为空', 1, 'regex', 3),
                array('content', 'require', '邮件内容不能为空', 1, 'regex', 3),
            );
            $model = M();
            if ($model->validate($rules)) {
                $post = I('post.', array(), 'trim');
                if (empty($post)) {
                    $this->error('请填写设置的值');
                }
                $result = x_send_email($post['send_to'], $post['subject'], $post['content']);
                if ($result && empty($result['error'])) {
                    $this->success('发送成功', U('mailTest'));
                } else {
                    $this->error('发送失败：' . $result['message']);
                }
            } else {
                $this->error($model->getError());
            }
        } else {
            $this->display();
        }
    }

    /*
     * 上传文件限制配置
     * */
    public function fileUpload()
    {
        if (IS_POST) {
            $post = I('post.', array(), 'trim');
            if (empty($post)) {
                $this->error('请填写设置的值');
            }
            $data = array(
                'key'   => self::UPLOAD_KEY,
                'value' => json_encode($post)
            );
            if ($this->setting_model->save($data) !== false) {
                $this->success('设置成功', U('fileUpload'));
            } else {
                $this->error('设置失败');
            }
        } else {
            $setting = $this->setting_model->getSettingByKey(self::UPLOAD_KEY);
            $this->assign('detail', $setting);
            $this->display();
        }
    }

    /*
     * 存储文件配置
     * */
    public function storage() {
        if (IS_POST) {
            $support_storages = array("Local", "Qiniu");
            $type =  I('post.type');
            $post = I('post.', array(), 'trim');
            if (empty($post)) {
                $this->error('请填写设置的值');
            }

            if (in_array($type, $support_storages)) {

                $data = array(
                    'key'   => self::STORAGE_KEY,
                    'value' => json_encode($post)
                );
                if ($this->setting_model->save($data) !== false) {
                    x_set_sys_config(array(
                        "FILE_UPLOAD_TYPE" => $type,
                        "UPLOAD_TYPE_CONFIG" => $post[$type])
                    );
                    $this->success('设置成功', U('storage'));
                } else {
                    $this->error('设置失败');
                }
            } else {
                $this->error("文件存储类型不存在");
            }


        } else {
            $setting = $this->setting_model->getSettingByKey(self::STORAGE_KEY);
            $this->assign('detail', $setting);
            $this->display();
        }
    }

    /*
     * 个人信息设置
     * */
    public function personalInfo() {


        $admin_model = D('Admin');
        if (IS_POST) {
            $_POST['admin_id']= x_get_admin_id();;
            $data = $admin_model
                ->field("admin_id,nicename,mobile,email")
                ->create();
            if ($data) {
                if ($admin_model->save()!==false) {
                    $this->success("修改成功！", U('personalInfo'));
                } else {
                    $this->error("修改失败！");
                }
            } else {
                $this->error($admin_model->getError());
            }

        } else {
            $info = $admin_model->getAdminByUsername($this->_admin['username']);
            $this->assign('info', $info);
            $this->display();
        }
    }

    /*
     * 个人密码设置
     * */
    public function personalPassword() {

        if (IS_POST) {

            $admin_id = x_get_admin_id();

            $old_password = I('post.old_password');
            $new_password = I('post.new_password');

            if (empty($old_password)) {
                $this->error("原始密码不能为空！");
            }
            if (empty($new_password)) {
                $this->error("新密码不能为空！");
            }
            $admin_model = D('Admin');
            $password_db = $admin_model->where(array('admin_id' => $admin_id))->getField('password');

            if ($password_db != x_encrypt_password($old_password)) {
                $this->error('旧密码错误');
            } elseif ($password_db == x_encrypt_password($new_password)) {
                $this->error('新密码不能和原始密码相同');
            } else {
                if ($admin_model->where("admin_id=%d", $admin_id)
                        ->save(array(
                                'password' => x_encrypt_password($new_password))
                        ) !== false) {
                    $this->success('修改密码成功', U('personalPassword'));
                } else {
                    $this->error('修改密码失败');
                }
            }
        } else {
            $this->display();
        }

    }
    /*
    public function index ()
    {
        if (IS_POST) {
            $configData = array();
            $data = (array_map('htmlspecialchars', I('post.')));
            foreach($data as $k => $v)
            {
                if (!preg_match('/^edit___cfg_/', $k)) {
                    continue;
                }
                $k = preg_replace('/^edit___cfg_/', '', $k);
                $this->config_model->where(array('name'=>$k))->setField('value',$v);
                $configData[$k]=htmlspecialchars_decode($v);
                //$config->add(array('name'=>$k,'value'=>$v));
            }
            $str=<<<php
<?php
return array(
//此配置项为自动生成请勿直接修改；如需改动请在后台网站设置
//*************************************网站设置****************************************
    'WEB_NAME'                  =>  '{$data['WEB_NAME']}',
    'WEB_KEYWORDS'              =>  '{$data['WEB_KEYWORDS']}',
    'WEB_DESCRIPTION'           =>  '{$data['WEB_DESCRIPTION']}',
    'WEB_POWERBY'               =>  '{$data['WEB_POWERBY']}',
    'WEB_BEIAN'                 =>  '{$data['WEB_BEIAN']}',
    'WEB_POWERBY'               =>  '{$data['WEB_POWERBY']}',
    'WEB_STATISTICS'            =>  '{$data['WEB_STATISTICS']}',
    'WEB_STATUS'                =>  '{$data['WEB_STATUS']}',
    'WEB_CLOSEWORD'             =>  '{$data['WEB_CLOSEWORD']}',

//*************************************水印设置****************************************
    'PHOTO_MARKUP'              =>  '{$data['PHOTO_MARKUP']}',
    'PHOTO_PIC_PATH'            =>  '{$data['PHOTO_PIC_PATH']}',
    'PHOTO_DIAPHANEITY'         =>  '{$data['PHOTO_DIAPHANEITY']}',
    'PHOTO_WATERTEXT'           =>  '{$data['PHOTO_WATERTEXT']}',
    'PHOTO_TTF_PATH'            =>  '{$data['PHOTO_TTF_PATH']}',
    'PHOTO_FONTSIZE'            =>  '{$data['PHOTO_FONTSIZE']}',
    'PHOTO_FONTCOLOR'           =>  '{$data['PHOTO_FONTCOLOR']}',
    'PHOTO_WATERPOS'            =>  '{$data['PHOTO_WATERPOS']}',

//*************************************邮件设置****************************************
    'SMTP_SERVER'               =>  '{$data['SMTP_SERVER']}',
    'SMTP_PORT'                 =>  '{$data['SMTP_PORT']}',
    'SMTP_USERMAIL'             =>  '{$data['SMTP_USERMAIL']}',
    'SMTP_PASSWORD'             =>  '{$data['SMTP_PASSWORD']}',
    'SMTP_USER'                 =>  '{$data['SMTP_USER']}',

//***********************************评论管理***********************************************
    'COMMENT_REVIEW'            =>  '{$data['COMMENT_REVIEW']}',
    'COMMENT_SENMAIL'           =>  '{$data['COMMENT_SENMAIL']}',
    'COMMENT_USEREMAIL'         =>  '{$data['COMMENT_USEREMAIL']}',

//*************************************第三方登录****************************************
    'QQ_APP_ID'                 =>  '{$data['QQ_APP_ID']}',            // QQ登陆APP D
    'QQ_APP_KEY'                =>  '{$data['QQ_APP_KEY']}',           // QQ登陆APP KEY
    'SINA_API_KEY'              =>  '{$data['SINA_API_KEY']}',         // 新浪登陆API KEY
    'SINA_SECRET'               =>  '{$data['SINA_SECRET']}',          // 新浪登陆SECRET
    'DOUBAN_API_KEY'            =>  '{$data['DOUBAN_API_KEY']}',       // 豆瓣登陆API KEY
    'DOUBAN_SECRET'             =>  '{$data['DOUBAN_SECRET']}',        // 豆瓣登陆SECRET
    'RENREN_API_KEY'            =>  '{$data['RENREN_API_KEY']}',       // 人人登陆API KEY
    'RENREN_SECRET'             =>  '{$data['RENREN_SECRET']}',        // 人人登陆SECRET
    'KAIXIN_API_KEY'            =>  '{$data['KAIXIN_API_KEY']}',       // 开心网登陆API KEY
    'KAIXIN_SECRET'             =>  '{$data['KAIXIN_SECRET']}',        // 开心网登陆SECRET
    'GITHUB_CLIENT_ID'          =>  '{$data['GITHUB_CLIENT_ID']}',     // github登陆API KEY
    'GITHUB_CLIENT_SECRET'      =>  '{$data['GITHUB_CLIENT_SECRET']}', // github登陆SECRET
    'SOHU_API_KEY'              =>  '{$data['SOHU_API_KEY']}',         // 搜狐网登陆API KEY
    'SOHU_SECRET'               =>  '{$data['SOHU_SECRET']}',          // 搜狐网登陆SECRT,
);
php;
            file_put_contents(APP_PATH.'/Common/Conf/webconfig.php', $str);
            $this->config_model->cleanCache();
            $this->success('操作成功', U('index'));
        } else {
            $this->assign('detail', $this->config_model->fetchAll());
            $this->display();
        }
    }
    */

}